import { useSyncExternalStore} from "react";

/**
 * 监听localStorage hook
 * @param key 存储到localstorage的key
 * @param defaultValue 默认值
 */
export const useStorage = (key: any, defaultValue?: any) => {
  const subscribe = (callback: any) => {
    window.addEventListener("storage", (e) => {
      console.log(e);
      callback(); // 触发react 响应
    });
    return () => window.removeEventListener("storage", callback);
  };

  // 获取数据
  const getSnapshot = () => {
    return (localStorage.getItem(key)? JSON.parse(localStorage.getItem(key)!) : null) || defaultValue;
  }

  // 修改数据
  const setStorage = (value: any) => {
    localStorage.setItem(key, JSON.stringify(value));
    window.dispatchEvent(new StorageEvent("storage")); // 当前页面需要 否则 事件不回响应

  }
  return [useSyncExternalStore(subscribe, getSnapshot), setStorage];
}